package vn.com.epi.sevlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/test-sql-server.html")
public class TestConnectServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public TestConnectServlet() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String message = "";
		try {
			String connectionUrl = "jdbc:sqlserver://10.30.11.29;databaseName=Recommendation;user=baomoi;password=baomoi2015";
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			Connection connection = DriverManager.getConnection(connectionUrl);
			if (connection != null) {
				DatabaseMetaData dm = (DatabaseMetaData) connection
						.getMetaData();
				message += "Driver name: " + dm.getDriverName() + "\n";
				message += "Driver version: " + dm.getDriverVersion() + "\n";
				message += "Product name: " + dm.getDatabaseProductName()
						+ "\n";
				message += "Product version: " + dm.getDatabaseProductVersion()
						+ "\n";
			}
		} catch (Exception e) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			message = sw.toString();
		}

		request.setAttribute("message", message);
		request.getRequestDispatcher("/WEB-INF/jsp/connect.jsp").forward(
				request, response);
	}

}
